package com.ssyc.common.quanzi;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.R;
import com.ssyc.common.adapter.ShowPicGvAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PickChooseManager;
import com.ssyc.common.manager.StateBarManager;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;
import okhttp3.Call;

/**
 * 发布圈子
 * Created by Administrator on 2018/6/25 0025.
 */

public class SendCircleActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    //返回
    private RelativeLayout rlBack;

    //发布
    private RelativeLayout rlAply;

    //输入内容的EditText
    private EditText etInput;

    //显示数字提示的TextView
    private TextView tvShownum;

    //展示选择图片的GridView
    private MyGridView mgv;

    //图片适配器
    private ShowPicGvAdapter adapter;

    //填充适配器的图片地址
    private List<String> mPicPaths;


    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return "";
    }

    @Override
    protected int getContentLayout() {
        return R.layout.base_activity_send_circle;
    }

    @Override
    protected void init() {

        showContent();

        //设置标题栏的颜色和状态
        initStateColor();

        //初始化视图
        initView();

        //设置监听
        initListener();

        //设置展示图片的适配器
        initGv();
    }


    /**
     * 配置状态栏颜色的方法
     */
    private void initStateColor() {
        //设置6.0以后沉浸状体栏的问题
        StateBarManager.setBarWithUltimateBar(this, getResources().getColor(com.ssyc.common.R.color.titlebg),
                getResources().getColor(com.ssyc.common.R.color.nav_color));
    }

    /**
     * 初始化视图
     */
    private void initView() {

        rlBack = findViewById(R.id.rl_back);
        rlBack.setOnClickListener(this);
        rlAply = findViewById(R.id.rl_aply);
        rlAply.setOnClickListener(this);

        etInput = findViewById(R.id.et_input);
        tvShownum = findViewById(R.id.tv_shownum);
        mgv = findViewById(R.id.mgv);
        tvBaseRight.setOnClickListener(this);
    }


    /**
     * 设置展示选择图片GridView
     */
    private void initGv() {
        mPicPaths = new ArrayList<>();
        adapter = new ShowPicGvAdapter(this, mPicPaths);
        mgv.setAdapter(adapter);
        mgv.setOnItemClickListener(this);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_back) {
            //返回
            finish();
        } else if (id == R.id.rl_aply) {
            rlAply.setClickable(false);
            //防止连点
            if (UiUtils.isNotFastClick()) {
                //发布
                doUploading();
            }
        }
    }

    /**
     * 先判断添加的内容的完整性
     * 然后做图片上传的操作
     */
    private void doUploading() {
        final String uploadText = etInput.getText().toString().trim();

        if (TextUtils.isEmpty(uploadText)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请输入内容...", 0).show();
            rlAply.setClickable(true);
            return;
        }

        if (mPicPaths == null || mPicPaths.size() == 0) {
            httpUpload(new ArrayList<File>(),uploadText);
            return;

        }else{
            //做压缩处理
            List<File> files = new ArrayList<>();
            for (int i = 0; i < mPicPaths.size(); i++) {
                File file = new File(mPicPaths.get(i));
                files.add(file);
            }

            UIHelper.showDialog(this, "上传中...");

            //使用Luban做压缩图片处理
            Luban.compress(this, files).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720).putGear(Luban.CUSTOM_GEAR).launch(new OnMultiCompressListener() {

                @Override
                public void onStart() {
                    //压缩开始
                }

                @Override
                public void onSuccess(List<File> fileList) {
                    //压缩成功后的回调,上传该集合的文件
                    httpUpload(fileList,uploadText);
                }

                @Override
                public void onError(Throwable e) {
                    //压缩错误
                }
            });
        }
    }

    /**
     * 发布圈子消息的网络请求
     */
    private void httpUpload(List<File> fileList,String uploadText) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("content",uploadText);
        map.put("platform", "8");
        Map<String, File> fileMap = new HashMap<>();
        for (int i = 0; i < fileList.size(); i++) {
            fileMap.put(System.currentTimeMillis() + i + i + ".jpg", fileList.get(i));
        }

        Log.i("test","SIZE:"+fileList.size());
        OkHttpUtils.post().url(HttpAdress.QUANZI).params(map).files("picture", fileMap).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("test", "错误信息是:" + e.toString());
                UiUtils.Toast("服务器异常,上传失败", false);
                CustomDialogManager.dissmiss();
                rlAply.setClickable(true);
            }

            @Override
            public void onResponse(String response, int id) {
                UIHelper.dismissDialog();
                UiUtils.Toast("上传成功", false);
                rlAply.setClickable(true);
                Log.i("test", "json:" + response);
                //第一步:通知朋友圈界面进行刷新操作
                BusInfo busInfo = new BusInfo();
                busInfo.setType(MyQuanziActivity.UPDATE);
                EventBus.getDefault().post(busInfo);
                finish();
            }
        });
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        Object itemAdapter = parent.getAdapter();
        if (itemAdapter instanceof ShowPicGvAdapter) {
            if (mPicPaths.size() != 9) {
                if (position == ((ShowPicGvAdapter) itemAdapter).getCount() - 1) {
                    PickChooseManager.startPhotoPickActivity(SendCircleActivity.this,
                            9 - mPicPaths.size());
                } else {
                    PickChooseManager.startShowBigActivity(SendCircleActivity.this, mPicPaths, position);
                }
            } else {
                PickChooseManager.startShowBigActivity(SendCircleActivity.this, mPicPaths, position);
            }
        }
    }


    /**
     * 请求图库后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                for (int i = 0; i < photos.size(); i++) {
                    mPicPaths.add(photos.get(i));
                }

                //通知适配器刷新
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 设置监听的方法
     */
    private void initListener() {
        //输入框的改变监听
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etInput.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tvShownum.setText("0/200");
                } else {
                    tvShownum.setText(inputText.length() + "/200");
                }
            }
        });
    }

}
